package com.gnerv.pabu.basic.core.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import sun.misc.BASE64Encoder;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.file.Paths;

public class QrCodeUtils {

    private QrCodeUtils() {
    }

    public static void encode() throws WriterException, IOException {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        //第一个参数为二维码的内容 第二个参数不变 第三 四 个参数依次为 宽高
        BitMatrix bitMatrix = qrCodeWriter.encode("https://www.gnerv.com", BarcodeFormat.QR_CODE, 150, 150);
        //将二维码保存为 png 本地图片。
        MatrixToImageWriter.writeToPath(bitMatrix, "png", Paths.get("E:\\qr.png"));

        //转化为流
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        MatrixToImageWriter.writeToStream(bitMatrix,"png",byteArrayOutputStream);

        byte[] bytes = byteArrayOutputStream.toByteArray();
        //生成的 base64Image
        String base64Image = new BASE64Encoder().encode(bytes);
        /**
         * 生成的 base64Image 我们可以在前端通过以下方式进行展示：
         * <img src="
         * rGY39gpOg6BxVoDGWQ0aewVorOQOzgeCARJVr9G/rzsB1YEfZgHh5QjIiPn1zoVTu6SsOLPIdMEh
         * 2BMxJ1lzK0FYq4GRqJgWt76V5e665Na1HQ1F09/oSIpu6qaIRxaztG5pOZXrmy1sRzPjqJ7EKIQ2
         * Ye27o8clD4ETJxrB0JHfg7xqOAvIrtgGGTFH3XhObS3ABTHn+UQXXAROTI88a04QGB6R8Q9e+QOH
         * lnNzjaH0oAAAAABJRU5ErkJggg=="  alt="">
         */
    }


    public static void main(String[] args) throws IOException, WriterException {
        QrCodeUtils.encode();
    }
}
